<template>
  <div class="caseHistory-container">
    <div class="caseHistory-left">
      <div class="caseHistory-title-container">
        <div class="title"><p class="title-con">就诊历史</p></div>
        <div class="btn">
          <div class="print-container">
            <el-checkbox v-model="isPrint"></el-checkbox>
            <el-select
              v-model="printType"
              placeholder="请选择"
              style="width: 110px"
            >
              <el-option
                v-for="item in printTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <el-button
            class="main-btn"
            size="small"
            type="primary"
            @click="submitCaseHistory"
            >保存</el-button
          >
          <el-button
            class="border-btn"
            size="small"
            @click="clearData"
            v-if="medicalType == 1 || registrationItem.register_status !== 3"
            >清空</el-button
          >
          <el-button class="border-btn" size="small" @click="outpatientSetOpen"
            >门诊设置</el-button
          >
          <!-- <el-button class="border-btn" size="small" @click="getRemindData"
            >获取提示数据</el-button
          > -->
        </div>
      </div>
      <div class="caseHistory-content-container">
        <case-content
          ref="caseContent"
          :optionsData="optionsData"
          :medicalType="medicalType"
        ></case-content>
      </div>
      <div class="prescription-content-container">
        <prescription
          ref="prescription"
          @printItemClick="printItemClick"
          @printCheckItemClick="printCheckItemClick"
        ></prescription>
      </div>

      <!-- <print ref="print"></print> -->
      <!-- 打印病历 -->
      <div class="print-container">
        <div id="app">
          <vue-easy-print tableShow ref="print">
            <!-- 你自己编写打印的模板  -->
            <template slot-scope="func">
              <div id="print">
                <!-- 打印处方 -->
                <prescription-print
                  ref="prescriptionPrint"
                  v-if="printType == 2"
                  :patientData="caseHistoryDetail"
                ></prescription-print>
                <!-- 打印病历 -->
                <case-print
                  ref="casePrint"
                  v-if="printType == 1"
                  :caseData="caseHistoryDetail"
                ></case-print>
              </div>
            </template>
          </vue-easy-print>
        </div>
      </div>
      <!-- 单个处方打印 -->
      <div class="print-container">
        <div id="app">
          <vue-easy-print tableShow ref="persPrint">
            <!-- 你自己编写打印的模板  -->
            <template slot-scope="func">
              <div id="print">
                <!-- 打印单个处方 -->
                <prescription-item-print
                  :patientData="caseHistoryDetail"
                  :presItem="presItem"
                ></prescription-item-print>
              </div>
            </template>
          </vue-easy-print>
        </div>
      </div>
      <!-- 单个检查项或单个附加费用打印 -->
      <div class="print-container">
        <div id="app">
          <vue-easy-print tableShow ref="checkItemPrint">
            <!-- 你自己编写打印的模板  -->
            <template slot-scope="func">
              <div id="print">
                <check-item-print
                  :patientData="caseHistoryDetail"
                  :printItemData="checkItemData"
                ></check-item-print>
              </div>
            </template>
          </vue-easy-print>
        </div>
      </div>
    </div>
    <div class="caseHistory-right">
      <medical-record :resumeId="resumeId"></medical-record>
    </div>
    <outpatient-set
      ref="outpatientSet"
      @comfrim-save="comfrimSave"
    ></outpatient-set>
  </div>
</template>
<script>
import print from "../../print/print";
import casePrint from "../../print/casePrint";
import prescriptionPrint from "../../print/prescriptionPrint";
import prescriptionItemPrint from "../../print/prescriptionItemPrint";
import checkItemPrint from "../../print/checkItemPrint";
import vueEasyPrint from "vue-easy-print";

import caseContent from "./caseContent";
import prescription from "./prescription";
import medicalRecord from "./medicalRecord";
import {
  createCaseHistory,
  updateCaseHistory,
  caseHistoryDetail,
  caseHistoryList,
} from "@/api/outpatient.js";
import { remindData } from "@/api/common.js";
export default {
  components: {
    print,
    caseContent,
    prescription,
    medicalRecord,
    vueEasyPrint,
    casePrint,
    prescriptionPrint,
    prescriptionItemPrint,
    checkItemPrint,
    outpatientSet: () => import("./outpatientSet"),
  },
  props: {
    // 是否快速就诊
    medicalType: {
      type: Number,
      default: 2, // 1,快速就诊，2，挂号后的普通就诊, 3,患者补病例 ,4,患者新增病例(传1)
    },
    // 患者id
    registrationItem: {
      type: Object,
      default: null,
    },
  },
  watch: {
    medicalType: {
      handler(newval, oldval0) {
        this.createCaseData.medical_record_type = newval;
        if (newval == 2 || newval == 4) {
          if (newval == 4) {
            this.createCaseData.medical_record_type = 1;
          }
          this.optionsData = { ...this.registrationItem, medical_repeat: 1 };
        } else {
          // 重置数据
          this.resetCaseData();
        }
      },
      immediate: true,
    },
    registrationItem: {
      handler(newval, oldval) {
        if (newval == null) {
          // 重置数据
          this.resetCaseData();
          return;
        } else {
          switch (newval.register_status) {
            case 3:
              this.getCaseHistoryDetail(newval.id, false);
              break;
            default:
              this.resumeId = newval.resume_id;
              // 病历处方清空
              this.registrationData();
              break;
          }
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      isPrint: false,
      resumeId: 0,
      optionsData: {
        tableData: [],
      },
      printType: 1,
      printTypeList: [
        {
          value: 1,
          label: "打印病历",
        },
        {
          value: 2,
          label: "打印处方",
        },
      ],
      // 空白数据结构
      resetData: {
        ID: 0, // 病历id

        register_id: 0, // 挂号单id
        register_no: "", // 挂号单编号

        medical_record_type: 1, // 1,快速就诊，2，挂号后的普通就诊

        real_name: "", // 患者名称
        id_card: "", // 患者身份证
        gender: "0", // 性别
        mobile: "", // 手机号
        tel: "", // 紧急联系方式
        age: [0, 0, 0], // 年龄
        birthday: "", // 出生日期
        address: "", // 地址
        resume_id: 0, // 患者id
        medical_describe: "", // 主诉
        past_history: "", // 既往史
        personal_history: "", // 个人史
        allergy_history: "", // 过敏史
        result: "", // 诊断结果

        temperature: "", // 温度
        weight: "", // 体重
        heart_rate: "", // 心率
        blood_pressure_1: "", // 血压
        blood_pressure_2: "",
        medical_others: "", // 其它体格检查内容

        medical_repeat: 1, // 1,初诊，2，复诊

        doctor_id: 0, // 医生id
        doctor_name: "", // 医生姓名
        department_name: "", // 医生科室
        department_id: 0,

        advice: "", // 医嘱
        medical_status: 1, // 病历状态， 1，就诊，2，归档

        check_items: [], // 检查治疗项
        surcharge: [], // 附加费用
        prescriptions: [], // 处方
      },
      // 新建病历--快速就诊
      createCaseData: {
        ID: 0, // 病历id

        register_id: 0, // 挂号单id
        register_no: "", // 挂号单编号

        medical_record_type: 1, // 1,快速就诊，2，挂号后的普通就诊

        real_name: "", // 患者名称
        id_card: "", // 患者身份证
        gender: "0", // 性别
        mobile: "", // 手机号
        tel: "", // 紧急联系方式
        contact: "", // 挂号紧急联系方式
        age: [0, 0, 0], // 年龄
        birthday: "", // 出生日期
        address: "", // 地址
        resume_id: 0, // 患者id
        medical_describe: "", // 主诉
        past_history: "", // 既往史
        personal_history: "", // 个人史
        allergy_history: "", // 过敏史
        result: "", // 诊断结果

        temperature: "", // 温度
        weight: "", // 体重
        heart_rate: "", // 心率
        blood_pressure_1: "", // 血压
        blood_pressure_2: "",
        medical_others: "", // 其它体格检查内容

        medical_repeat: 1, // 1,初诊，2，复诊

        doctor_id: 0, // 医生id
        doctor_name: "", // 医生姓名
        department_name: "", // 医生科室
        department_id: 0,

        advice: "", // 医嘱
        medical_status: 1, // 病历状态， 1，就诊，2，归档

        check_items: [], // 检查治疗项
        surcharge: [], // 附加费用
        prescriptions: [], // 处方
      },
      caseHistoryDetail: null,
      caseTableData: [],
      presItem: null,
      checkItemData: null,
      userInfo: null,
    };
  },
  created() {
    console.log(this.medicalType, this.optionsData);
    this.caseTableData = this.$store.getters.userHabit.checkedField;
    console.log(this.caseTableData);
    this.getRemindData();
    this.userInfo = this.$store.getters.userInfo;
    this.doctorInfo();
  },
  methods: {
    printItemClick(itmval) {
      this.presItem = itmval;
      setTimeout(() => {
        this.$refs.persPrint.print();
      }, 100);
    },
    printCheckItemClick(itm) {
      this.checkItemData = itm;
      setTimeout(() => {
        this.$refs.checkItemPrint.print();
      }, 100);
    },
    doctorInfo() {
      this.createCaseData.doctor_id = this.userInfo.id;
      this.createCaseData.doctor_name = this.userInfo.real_name;
      this.createCaseData.department_id = this.userInfo.department
        ? this.userInfo.department.ID
        : 0;
      this.createCaseData.department_name = this.userInfo.department
        ? this.userInfo.department.DepartmentName
        : "";

      this.resetData.doctor_id = this.userInfo.id;
      this.resetData.doctor_name = this.userInfo.real_name;
      this.resetData.department_id = this.userInfo.department
        ? this.userInfo.department.ID
        : 0;
      this.resetData.department_name = this.userInfo.department
        ? this.userInfo.department.DepartmentName
        : "";
    },
    clearData() {
      // 重置挂号带来的基本信息
      if (this.medicalType == 1) {
        this.optionsData = { ...this.resetData, age: [0, 0, 0] };
      }
      // 清除病历和检查项
      this.$nextTick(() => {
        this.clearCase();
        this.clearCheckItem();
        this.clearPrescriptions();
        this.clearAdvice();
        this.clearSurcharge();
      });
    },
    getRemindData() {
      remindData().then((res) => {
        if (res.code == 200) {
          console.log(res.data);
        }
      });
    },
    outpatientSetOpen() {
      this.$refs.outpatientSet.openDialog();
    },
    // 清空病例
    clearCase() {
      this.$nextTick(() => {
        let casesdata = this.$refs.caseContent.caseData;
        casesdata.forEach((itm, idx) => {
          if (itm.name !== "tigejiancha") {
            itm.value = "";
          } else {
            itm.value = {
              temperature: "",
              weight: "",
              heart_rate: "",
              blood_pressure_1: "",
              blood_pressure_2: "",
              medical_others: "",
            };
          }
        });
      });
    },
    // 给子组件病历赋值
    assignCase(data) {
      let cases = this.$refs.caseContent.caseData;
      cases.forEach((itm, idx) => {
        if (itm.name !== "tigejiancha") {
          itm.value = data[itm.name];
        } else {
          itm.value = {
            temperature: data.temperature,
            weight: data.weight,
            heart_rate: data.heart_rate,
            blood_pressure_1: data.blood_pressure_1,
            blood_pressure_2: data.blood_pressure_2,
            medical_others: data.medical_others,
          };
        }
      });
    },
    optionsDataOp() {
      this.optionsData.register_id = this.registrationItem.id;
      this.optionsData.register_no = this.registrationItem.no;
      this.optionsData.real_name = this.registrationItem.real_name;
      this.optionsData.age = this.registrationItem.age;
      this.optionsData.gender = this.registrationItem.gender;
      this.optionsData.doctor_id =
        this.registrationItem.doctor_id || this.userInfo.id;
      this.optionsData.doctor_name =
        this.registrationItem.doctor_name || this.userInfo.real_name;
      this.optionsData.department_id =
        this.registrationItem.department_id ||
        (this.userInfo?.department ? this.userInfo.department.ID : 0);
      this.optionsData.department_name =
        this.registrationItem.department_name ||
        (this.userInfo?.department
          ? this.userInfo.department.DepartmentName
          : "");
      this.optionsData.mobile = this.registrationItem.mobile;
      this.optionsData.tel = this.registrationItem.tel;
      this.optionsData.id_card = this.registrationItem.id_card;
      this.optionsData.address = this.registrationItem.address || "";
      // 如果不是已诊都默认为初诊
      if (this.registrationItem.register_status !== 3) {
        this.optionsData.medical_repeat = 1;
      }
    },
    // 未接诊，把挂号的信息付给病历中的字段
    registrationData() {
      if (this.registrationItem) {
        this.optionsDataOp();
        if (this.registrationItem.register_status !== 3) {
          this.$nextTick(() => {
            this.clearCase();
            this.clearCheckItem();
            this.clearPrescriptions();
            this.clearAdvice();
            this.clearSurcharge();
          });
        }
      }
    },
    resetCaseData() {
      // 重置挂号带来的基本信息
      this.optionsData = { ...this.resetData, age: [0, 0, 0] };
      // 清除病历和检查项
      this.$nextTick(() => {
        this.clearCase();
        this.clearCheckItem();
        this.clearPrescriptions();
        this.clearAdvice();
        this.clearSurcharge();
        this.resumeId = 0;
      });
    },
    // 检查项清除
    clearCheckItem() {
      let checkItem = this.$refs.prescription.checkItemsForm;
      checkItem.check_items = [];
    },
    // 检查项赋值
    assignCheckItem(data) {
      let checkItem = this.$refs.prescription.checkItemsForm;
      let datas = data.check_items || [];
      datas.forEach((itm, idx) => {
        Object.assign(itm, { update_status: 0 });
      });
      checkItem.check_items = datas;
    },
    clearPrescriptions() {
      this.$refs.prescription.chengyaoList = [];
      this.$refs.prescription.yinpianList = [];
      this.$refs.prescription.shuyeList = [];
      this.$refs.prescription.payedChengyaoList = [];
      this.$refs.prescription.payedYinpianList = [];
      this.$refs.prescription.payedShuyeList = [];
    },
    // 处方赋值
    assignPrescriptions(data) {
      // 给处方赋值前先清空
      this.$refs.prescription.chengyaoList = [];
      this.$refs.prescription.yinpianList = [];
      this.$refs.prescription.shuyeList = [];
      this.$refs.prescription.payedChengyaoList = [];
      this.$refs.prescription.payedYinpianList = [];
      this.$refs.prescription.payedShuyeList = [];
      if (data.prescriptions && data.prescriptions.length > 0) {
        let chengyaoList = [];
        let yinpianList = [];
        let shuyeList = [];
        let payedChengyaoList = [];
        let payedYinpianList = [];
        let payedShuyeList = [];
        data.prescriptions.forEach((item, index) => {
          if (item.category_key == "cycf") {
            let cyItem = {
              ID: item.ID,
              update_status: 0,
              prescription_name: "",
              category_key: "cycf",
              category_name: "成药处方",
              prescription_status: item.prescription_status,
              details: item.details,
              remark: null,
            };
            if (item.prescription_status == 2) {
              payedChengyaoList.push(cyItem);
            } else {
              chengyaoList.push(cyItem);
            }
          }
          if (item.category_key == "ypcf") {
            let ypItem = {
              ID: item.ID,
              update_status: 0,
              prescription_name: "",
              category_key: "ypcf",
              category_name: "饮片处方",
              prescription_status: item.prescription_status,
              details: item.details,
              remark: item.remark[1],
            };
            if (item.prescription_status == 2) {
              payedYinpianList.push(ypItem);
            } else {
              yinpianList.push(ypItem);
            }
          }
          if (item.category_key == "sycf") {
            let syItem = {
              ID: item.ID,
              update_status: 0,
              prescription_name: "",
              category_key: "sycf",
              category_name: "输液处方",
              prescription_status: item.prescription_status,
              group: [],
            };
            for (const key in item.remark) {
              let gitem = {
                price_amount: 0,
                details: [],
                remark: {},
              };
              let list = item.details.filter((p) => p.group == Number(key));
              list.forEach((g, gi) => {
                gitem.price_amount += g.amount;
              });
              gitem.details = list;
              gitem.remark = item.remark[key];

              syItem.group.push(gitem);
            }

            if (item.prescription_status == 2) {
              payedShuyeList.push(syItem);
            } else {
              shuyeList.push(syItem);
            }
          }
        });
        this.$refs.prescription.chengyaoList = chengyaoList;
        this.$refs.prescription.yinpianList = yinpianList;
        this.$refs.prescription.shuyeList = shuyeList;
        this.$refs.prescription.payedChengyaoList = payedChengyaoList;
        this.$refs.prescription.payedYinpianList = payedYinpianList;
        this.$refs.prescription.payedShuyeList = payedShuyeList;
      }
    },
    // 检查项清除
    clearAdvice() {
      this.$refs.prescription.advice = "";
    },
    // 检查项赋值
    assignAdvice(data) {
      this.$refs.prescription.advice = data.advice;
    },
    // 附加费用清除
    clearSurcharge() {
      this.$refs.prescription.surchargeList = [];
      this.$refs.prescription.payedSurchargeList = [];
    },
    // 附加费用赋值
    assignSurcharge(data) {
      let datas = data.surcharge || [];
      let payedSurcharge = [];
      let surcharge = [];
      datas.forEach((itm, idx) => {
        Object.assign(itm, { update_status: 0 });
        if (itm.surcharge_status == 2) {
          payedSurcharge.push(itm);
        } else {
          surcharge.push(itm);
        }
      });
      this.$refs.prescription.surchargeList = surcharge;
      this.$refs.prescription.payedSurchargeList = payedSurcharge;
    },
    getCaseHistoryDetail(registerid, print) {
      var that = this;
      that.caseHistoryDetail = null;
      caseHistoryDetail(registerid).then((res) => {
        that.caseHistoryDetail = res.data;

        if (that.caseHistoryDetail) {
          that.caseHistoryDetail.age = res.data.age
            ? res.data.age.split(",").map((value) => {
                return Number(value);
              })
            : [];

          that.resumeId = that.caseHistoryDetail.resume_id;
          // 挂号信息赋值
          that.optionsData = that.caseHistoryDetail;
          // 病历赋值
          that.assignCase(that.caseHistoryDetail);
          // 检查项赋值
          that.assignCheckItem(that.caseHistoryDetail);
          // 处方赋值
          that.assignPrescriptions(that.caseHistoryDetail);
          // 医嘱赋值
          that.assignAdvice(that.caseHistoryDetail);
          // 附加费用
          that.assignSurcharge(that.caseHistoryDetail);
          if (that.isPrint && print) {
            console.log(that.caseHistoryDetail);
            // 判断有无可打印的处方
            if (
              that.printType == 2 &&
              that.caseHistoryDetail.check_items.length == 0 &&
              that.caseHistoryDetail.prescriptions.length == 0 &&
              that.caseHistoryDetail.surcharge.length == 0
            ) {
              that.$message({
                type: "error",
                message: "暂无可打印的处方",
                duration: 1500,
              });
              return;
            }
            setTimeout(() => {
              that.$refs.print.print();
            }, 500);
          }
        } else {
          that.optionsDataOp();
          that.clearCase();
          that.clearCheckItem();
          that.clearPrescriptions();
          that.clearAdvice();
          that.clearSurcharge();
        }
      });
    },
    dataCheck() {
      if (!this.createCaseData.medical_describe) {
        this.$alert("请填写患者主诉", "温馨提示", {
          confirmButtonText: "确定",
          callback: (action) => {},
        });
        return true;
      }
      if (!this.createCaseData.result) {
        this.$alert("请填写诊断结果", "温馨提示", {
          confirmButtonText: "确定",
          callback: (action) => {},
        });
        return true;
      }
    },
    submitCaseHistory() {
      // 重构要提交的数据
      this.caseDataOption();
      let baseinfo = this.$refs.caseContent.formDataValidator();
      // 提交数据前，校验患者基本信息格式是否正确
      if (!baseinfo) {
        return;
      }
      // 判断病例必填项是否填写
      if (this.dataCheck()) {
        return;
      }
      if (this.registrationItem && this.registrationItem.register_status == 3) {
        this.updateCaseHistorySub();
      } else {
        this.createCaseHistorySub();
      }
    },
    // 处理病历数据
    caseDataOption() {
      var that = this;
      // 判断提交病例类型--新增、普通就诊、补写、
      if (this.medicalType == 4) {
        this.createCaseData.medical_record_type = 1;
      } else {
        this.createCaseData.medical_record_type = this.medicalType;
      }
      // 给患者基本信息赋值
      if (this.medicalType !== 1) {
        if (this.registrationItem.register_status == 3) {
          if (this.caseHistoryDetail) {
            this.createCaseData.ID = this.caseHistoryDetail.ID;
            this.createCaseData.resume_id = this.caseHistoryDetail.resume_id;
            this.createCaseData.doctor_id =
              this.caseHistoryDetail.doctor_id || this.userInfo.id;
            this.createCaseData.doctor_name =
              this.caseHistoryDetail.doctor_name || this.userInfo.real_name;
            this.createCaseData.department_id = this.caseHistoryDetail.department_id;
            this.createCaseData.department_name = this.caseHistoryDetail.department_name;
            this.createCaseData.register_id = this.caseHistoryDetail.register_id;
            this.createCaseData.register_no = this.caseHistoryDetail.register_no;
            this.createCaseData.created_at = this.caseHistoryDetail.created_at; // 病例创建时间
          }
        } else {
          this.createCaseData.ID = 0;
          this.createCaseData.register_id = this.registrationItem.id;
          this.createCaseData.register_no = this.registrationItem.no;
          this.createCaseData.resume_id = this.registrationItem.resume_id || 0;
          this.createCaseData.doctor_id =
            this.registrationItem.doctor_id || this.userInfo.id;
          this.createCaseData.doctor_name =
            this.registrationItem.doctor_name || this.userInfo.real_name;
          this.createCaseData.department_id =
            this.registrationItem.department_id ||
            (this.userInfo?.department ? this.userInfo.department.ID : 0);
          this.createCaseData.department_name =
            this.registrationItem.department_name ||
            (this.userInfo?.department
              ? this.userInfo.department.DepartmentName
              : "");
        }
      } else {
        this.createCaseData.ID = 0;
      }

      this.createCaseData.real_name = this.optionsData.real_name;
      this.createCaseData.gender = this.optionsData.gender;
      this.createCaseData.age = this.optionsData.age.toString();
      this.createCaseData.mobile = this.optionsData.mobile;
      this.createCaseData.id_card = this.optionsData.id_card;
      this.createCaseData.address = this.optionsData.address;
      this.createCaseData.medical_repeat = this.optionsData.medical_repeat;
      this.createCaseData.tel = this.optionsData.tel;

      // 1，拿到病历数据内容
      let caseData = this.$refs.caseContent.emitCaseData();
      caseData.forEach((item, index) => {
        if (item.name !== "tigejiancha") {
          this.createCaseData[item.name] = item.value;
        } else {
          this.createCaseData.temperature = item.value.temperature;
          this.createCaseData.weight = item.value.weight;
          this.createCaseData.heart_rate = item.value.heart_rate;
          this.createCaseData.blood_pressure_1 = item.value.blood_pressure_1;
          this.createCaseData.blood_pressure_2 = item.value.blood_pressure_2;
          this.createCaseData.medical_others = item.value.medical_others;
        }
      });

      // 2，拿到处方数据
      let prescription = this.$refs.prescription.emitPrescriptionData();
      let chengyaoList = prescription.payedChengyaoList.concat(
        prescription.chengyaoList
      );
      let yinpianList = prescription.payedYinpianList.concat(
        prescription.yinpianList
      );
      let shuyeList = prescription.payedShuyeList.concat(
        prescription.shuyeList
      );
      let prescriptionSub = []; // 要提交的处方数据
      let surchargeList = []; // 附加费用
      let checkItemList = []; // 检查项
      // 过滤掉空检查项
      prescription.check_items.forEach((che, cheidx) => {
        if (che.check_item_name) {
          checkItemList.push(che);
        }
      });
      // 过滤附加费用
      prescription.surchargeList.forEach((sur, suridx) => {
        if (sur.surcharge_name) {
          sur.amount = Number(sur.amount);
          surchargeList.push(sur);
        }
      });
      this.createCaseData.check_items = checkItemList;
      this.createCaseData.advice = prescription.advice;
      this.createCaseData.surcharge = prescription.payedSurchargeList.concat(
        surchargeList
      );
      Object.assign(this.createCaseData, {
        delete_items: prescription.delete_items,
      });
      if (chengyaoList.length > 0) {
        chengyaoList.forEach((itm, idx) => {
          let detail = JSON.parse(JSON.stringify(itm.details));
          let detailList = [];
          detail.forEach((m, i) => {
            m.single_dose = Number(m.single_dose);
            m.number = Number(m.number);
            m.price = Number(m.price);
            m.amount = Number(m.amount);
            if (m.product_name !== "" && m.product_name !== undefined) {
              detailList.push(m);
            }
          });
          let subItem = {
            ID: itm.ID,
            update_status: itm.update_status,
            prescription_name: "",
            category_key: "cycf",
            category_name: "成药处方",
            details: detailList,
            remark: null,
          };
          if (detailList.length) {
            prescriptionSub.push(subItem);
          }
        });
      }
      if (yinpianList.length > 0) {
        yinpianList.forEach((itm, idx) => {
          let detail = JSON.parse(JSON.stringify(itm.details));
          let detailList = [];
          detail.forEach((m, i) => {
            m.single_dose = Number(m.single_dose);
            m.number = Number(m.number);
            m.price = Number(m.price);
            m.amount = Number(m.amount);
            if (m.product_name !== "" && m.product_name !== undefined) {
              detailList.push(m);
            }
          });
          let subItem = {
            ID: itm.ID,
            update_status: itm.update_status,
            prescription_name: "",
            category_key: "ypcf",
            category_name: "饮片处方",
            details: detailList,
            remark: {
              1: itm.remark,
            },
            group_count: 1,
          };
          if (detailList.length) {
            prescriptionSub.push(subItem);
          }
        });
      }
      if (shuyeList.length > 0) {
        shuyeList.forEach((itm, idx) => {
          console.log(itm);
          let subItem = {
            ID: itm.ID,
            update_status: itm.update_status,
            prescription_name: "",
            category_key: "sycf",
            category_name: "输液处方",
            details: [],
            remark: {},
            group_count: itm.group.length,
          };
          itm.group.forEach((gitm, gidx) => {
            let detail = JSON.parse(JSON.stringify(gitm.details));
            let detailList = [];
            detail.forEach((m, i) => {
              m.single_dose = Number(m.single_dose);
              m.number = Number(m.number);
              m.price = Number(m.price);
              m.amount = Number(m.amount);
              m.group = gidx + 1;
              if (m.product_name !== "" && m.product_name !== undefined) {
                subItem.details.push(m);
              }
            });
            // 组下的是否有药品
            let groupDetail = detail.some((p) => p.product_name !== "");
            if (groupDetail) {
              Object.assign(subItem.remark, { [gidx + 1]: gitm.remark });
            }
          });
          if (subItem.details.length) {
            prescriptionSub.push(subItem);
          }
        });
      }
      console.log(prescription, prescriptionSub);
      this.createCaseData.prescriptions = prescriptionSub;
    },
    // 创建病历
    createCaseHistorySub() {
      var that = this;
      // 快速就诊
      if (this.medicalType == 1) {
        this.createCaseData.ID = 0;
        this.createCaseData.register_id = 0;
        this.createCaseData.resume_id = 0;
      }
      this.createCaseData.created_at = new Date();
      createCaseHistory(that.createCaseData).then((res) => {
        if (res.code == 200) {
          let resdata = res.data;
          that.$emit("caseSuccess", that.medicalType, resdata);
          that.$message({
            type: "success",
            message: "保存成功",
            duration: 1500,
            onClose: () => {
              if (that.medicalType !== 1) {
                that.getCaseHistoryDetail(
                  resdata.register_id,
                  true
                );
              } else {
                that.createCaseData = resdata;
                that.caseHistoryDetail = resdata;
                if (that.isPrint) {
                  // 判断有无可打印的处方
                  if (
                    that.printType == 2 &&
                    that.caseHistoryDetail.check_items.length == 0 &&
                    that.caseHistoryDetail.prescriptions.length == 0 &&
                    that.caseHistoryDetail.surcharge.length == 0
                  ) {
                    that.$message({
                      type: "error",
                      message: "暂无可打印的处方",
                      duration: 1500,
                    });
                    return;
                  }
                  setTimeout(() => {
                    that.$refs.print.print();
                  }, 200);
                }
              }
            },
          });
        } else {
          that.$message({
            type: "success",
            message: res.msg,
            duration: 1500,
          });
        }
      });
    },
    // 修改病历
    updateCaseHistorySub() {
      var that = this;
      updateCaseHistory(that.createCaseData).then((res) => {
        if (res.code == 200) {
          that.$message({
            type: "success",
            message: "保存成功",
            duration: 1500,
            onClose: () => {
              // that.caseHistoryDetail = that.createCaseData;
              that.getCaseHistoryDetail(this.createCaseData.register_id, true);
              // if (that.isPrint) {
              //   setTimeout(() => {
              //     that.$refs.print.print();
              //   }, 200);
              // }
            },
          });
        } else {
          that.$message({
            type: "success",
            message: res.msg,
            duration: 1500,
          });
        }
      });
    },
    // 门诊设置
    comfrimSave(data) {
      let that = this;
      let setdata = data;
      // 诊断和主诉必须有的
      let zhusu = {
        sort: 1,
        title: "主诉",
        name: "medical_describe",
        value: "",
      };
      let zhenduan = {
        sort: 10,
        title: "诊断",
        name: "result",
        value: "",
      };
      let zs =
        setdata.checkedField.findIndex(
          (p) => JSON.parse(p).name == zhusu.name
        ) < 0;
      let zd =
        setdata.checkedField.findIndex(
          (p) => JSON.parse(p).name == zhenduan.name
        ) < 0;
      if (zs) {
        setdata.checkedField.unshift(JSON.stringify(zhusu));
      }
      if (zd) {
        setdata.checkedField.push(JSON.stringify(zhenduan));
      }
      setdata.checkedField.forEach((itm, idx) => {
        let itms = JSON.parse(itm);
        if (itms.name == "tigejiancha") {
          itms.value = {
            temperature: "",
            weight: "",
            heart_rate: "",
            blood_pressure_1: "",
            blood_pressure_2: "",
            medical_others: "",
          };
        } else {
          itms.value = "";
        }
        this.$set(setdata.checkedField, idx, itms);
      });
      console.log(setdata);
      this.$store.dispatch("personalSt/setHabitSetting", setdata).then(() => {
        console.log(this.$refs);
        that.$refs.caseContent.reload();
        that.$refs.prescription.prescriptionBtnShow();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/scss/outpatient/modules/caseHistory.scss";
</style>
